package com.base.jdbc.connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.base.jdbc.consts.JdbcConstas;

public class MysqlDbFactory {

	private MysqlDbFactory() {

	}

	public static void instance() {

	}

	private static Connection con;

	/**
	 * this method to init the con  and create the object
	 * @return
	 */
	public static Connection getCon() {
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url = JdbcConstas.MYSQL_URL;
		String username = JdbcConstas.MYSQL_USERNAME;
		String password = JdbcConstas.MYSQL_PASSWD;
		try {
			con = DriverManager.getConnection(url, username, password);
		} catch (SQLException se) {
			se.printStackTrace();
		}
		return con;
	}

	/**
	 * TODO 用来扩展链接池
	 * here to write the con pool!
	 * @return
	 */
	public synchronized static Connection getInstance() {
		if (con == null) {
			return getCon();
		}
		return con;

	}

	/**
	 * this is a method to get a new instance which is PreparedStatement
	 * 》》get PreparedStatement
	 * @param sql
	 * @return
	 * @throws SQLException
	 */
	public static PreparedStatement getStatment(String sql) throws SQLException {
		Connection con = getInstance();
		return con.prepareStatement(sql);
	}
	
	public static void close(PreparedStatement stat ,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(stat!=null){
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}


}
